import Application from "koa"
import { HttpException, MaxFileSize } from "./http-exception"
import fs from "fs/promises"

export default async (ctx: Application.DefaultState, next: () => any) => {
    try {
        await next()
    } catch (err: any) {
        let {
            code,
            errorCode,
            msg
        } = err
        const isHttpException = err instanceof HttpException

        if (isHttpException) {
            if (global.token) {
                errorCode = 10016
            }
            ctx.body = {
                errorCode,
                msg,
                token: global.token,
                request: `${ctx.method} ${ctx.path}`
            }
            ctx.state = code
        } else {
            if (err.message.includes('options.maxFileSize')) {
                ctx.body = new MaxFileSize()
            } else {
                console.log(err)
                const url = `${process.cwd()}/err.txt`
                const data = await fs.readFile(url, {
                    encoding: 'utf-8'
                });
                await fs.writeFile(url, `${data}
    ${new Date()}---------------------------------------------------------
    ${err.stack}`)
                console.log(`错误日志已生成，位置为${url}`)
                ctx.body = {
                    errorcode: '00000',
                    msg: '服务器存在未知错误'
                }
            }
        }
    }
}